package practice1_100;

public class Practice59 {
    public int[][] generateMatrix(int n) {
        int[][] matrix=new int[n][n];
        int columnBeg=0,rowBeg=0,columnEnd=n-1,rowEnd=n-1;
        int count=1;
        while (count<=n*n&&columnBeg<=columnEnd&&rowBeg<=rowEnd){
            for (int i = columnBeg; i <columnEnd&&count<=n*n ; i++) {
                matrix[rowBeg][i]=count;
                count++;
            }
            for (int i = rowBeg; i <rowEnd&&count<=n*n ; i++) {
                matrix[i][columnEnd]=count;
                count++;
            }
            for (int i = columnEnd; i >columnBeg&&count<=n*n ; i--) {
                matrix[rowEnd][i]=count;
                count++;
            }
            for (int i = rowEnd; i >rowBeg&&count<=n*n ; i--) {
                matrix[i][columnBeg]=count;
                count++;
            }
            columnBeg++;
            columnEnd--;
            rowBeg++;
            rowEnd--;
        }
        if(n%2==1) matrix[matrix.length/2][matrix.length/2]=count;
        return matrix;
    }

    public static void main(String[] args) {
        int[][] a =new Practice59().generateMatrix(5);
        System.out.println(a);
    }
}
